package test1;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
/*
	文件file1的内容
	Deer Bear River
	Car Car River
	Deer Car Bear
	
	输出结果 《单词计数》
	3,3
	4,4
	5,2

 */
public class WorkCount1 {
	public static class MyMapper extends Mapper<Object,Text,Text,IntWritable>{
		private static IntWritable iw=new IntWritable(1);
		private Text word=new Text();
		public void map(Object key,Text value,Context context) throws IOException,InterruptedException{
			StringTokenizer sto=new StringTokenizer(value.toString());
			while(sto.hasMoreTokens()){
				word.set(sto.nextToken().length()+"");//单个单词长度
				context.write(word, iw);
			}
		}
	}
	public static class MyReducer extends Reducer<Text,IntWritable,Text,IntWritable>{
		private IntWritable in=new IntWritable();
		public void reduce(Text key,Iterable<IntWritable> values,Context context)throws IOException,InterruptedException{
			int sum=0;
			for(IntWritable val:values){
				sum+=val.get();
			}
			in.set(sum);
			context.write(key, in);
		}
	}
	
	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Configuration conf=new Configuration();
		String[] str=new GenericOptionsParser(conf, args).getRemainingArgs();
		if(str.length!=2){
			System.err.println("Have an err！！！");
			System.exit(2);
		}
		Job job = new Job(conf,"word count");  
		job.setJarByClass(WorkCount1.class);  
		job.setMapperClass(MyMapper.class);  
		job.setReducerClass(MyReducer.class);  
		job.setOutputKeyClass(Text.class);  
		job.setOutputValueClass(IntWritable.class);
		FileInputFormat.addInputPath(job,new Path(str[0])); 
		FileOutputFormat.setOutputPath(job,new Path(str[1])); 
		System.exit(job.waitForCompletion(true)?0:1);  
	}
}